package controllers

import (
	"luckapi/models"
	"encoding/json"

	"github.com/astaxie/beego"
	"luckapi/mutils"
)

// Operations about Users
type UserController struct {
	beego.Controller
}

func (c *UserController) UrlMapping()  {
	c.Mapping("userinfo", c.UserInfo)
	c.Mapping("gamejoiner",c.GameJoiner)
}

// UserInfo ...
// @Title UserInfo
// @Description userinfo
// @Param	body		body 	models.User	true		"body for User content"
// @Success 201 {int} models.User
// @Failure 403 body is empty
// @router /userinfo [post,get]
func (c *UserController) UserInfo() {
	mutils.MLog(string(c.Ctx.Input.RequestBody))
	var v map[string]string
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		name := v["name"]
		if len(name) == 0 {
			c.Data["json"] = map[string]interface{}{"code":mutils.ErrorCode_Req_Parmas_NoMatch,"message":"参数错误"}
		}else {
			user, err := models.GetPersonByName(name)
			if err.Code != mutils.ResponseCode_Success {
				c.Data["json"] = map[string]interface{}{"code":err.Code,"message":err.Message}
			} else {
				c.Data["json"] = map[string]interface{}{"code":mutils.ResponseCode_Success,"message":"Success","data":map[string]interface{}{"user":user}}
			}
		}
	} else {
		apiError := mutils.ApiErrorWithErrorInfo(err,mutils.ErrorCode_Req_Params_NoJson)
		c.Data["json"] = map[string]interface{}{"code":apiError.Code,"message":apiError.Message}
	}
	c.ServeJSON()
}


// GameJoiner ...
// @Title GameJoiner
// @Description joiners
// @Param	body		body 	models.User	true		"body for User content"
// @Success 201 {int} models.Joiner
// @Failure 403 body is empty
// @router /gamejoiner [post,get]
func (c *UserController) GameJoiner()  {
	mutils.MLog(string(c.Ctx.Input.RequestBody))
	var res map[string]int
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &res); err == nil {
		gameid := res["gameid"]

		err, joiners := models.GetJoinerListByGameId(gameid)

		if err.Code == mutils.ResponseCode_Success {
			c.Data["json"] = map[string]interface{}{"code":mutils.ResponseCode_Success,"message":"Success","data":map[string]interface{}{"joiners":joiners}}
		} else {
			c.Data["json"] = map[string]interface{}{"code":err.Code,"message":err.Message,"data":map[string]interface{}{}}
		}
	}
	c.ServeJSON()
}
